package cn.yyt.yytravel.community.service.impl;

import cn.yyt.yytravel.community.mapper.CommunityMapper;
import cn.yyt.yytravel.community.mapper.LikeCommunityMapper;
import cn.yyt.yytravel.community.pojo.dto.CommunityQuery;
import cn.yyt.yytravel.community.pojo.dto.CommunitySaveParam;
import cn.yyt.yytravel.community.pojo.dto.LikeCommunityParam;
import cn.yyt.yytravel.community.pojo.entity.Community;
import cn.yyt.yytravel.community.pojo.vo.CommunityVO;
import cn.yyt.yytravel.community.pojo.vo.LikeCommunityVO;
import cn.yyt.yytravel.community.service.CommunityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunityServiceImpl implements CommunityService {
    @Autowired
    CommunityMapper communityMapper;

    @Autowired
    LikeCommunityMapper likeCommunityMapper;

    @Override
    public Community save(CommunitySaveParam communitySaveParam) {
        Community community = new Community();
        BeanUtils.copyProperties(communitySaveParam,community);
        community.setCreateTime(new Date());
        communityMapper.insertCommunity(community);
        return community;
    }

    @Override
    public List<CommunityVO> selectCommunity(CommunityQuery communityQuery) {
        List<CommunityVO> list = communityMapper.selectCommunity(communityQuery);
        String username = communityQuery.getUsername();
        System.out.println("--"+username);
        List<LikeCommunityVO> list2 = likeCommunityMapper.selectLikeCommunity(username);
        if (list2.get(0) == null){
            for (int i = 0; i < list.size(); i++) {
                    list.get(i).setLikeStatue(false);
            }
            return list;
        }
        // 使用Stream API来提取所有的communityId
        List<Long> communityIds = list2.stream()
                .map(LikeCommunityVO::getCommunityId) // 将每个LikeCommunityVO对象映射到其communityId
                .collect(Collectors.toList()); // 收集结果到一个新的List中
        for (int i = 0; i < list.size(); i++) {
            if (communityIds.contains(list.get(i).getId())){
                list.get(i).setLikeStatue(true);
            }else {
                list.get(i).setLikeStatue(false);
            }
        }
        return list;
    }

    @Override
    public void deleteCommunity(Long id) {
        communityMapper.deleteCommunity(id);
    }

    @Override
    public void saveLikeC(LikeCommunityParam likeCommunityParam) {
        likeCommunityMapper.saveLikeMC(likeCommunityParam);
    }

    @Override
    public List<CommunityVO> selectLikeCommunity(CommunityQuery communityQuery) {
        return null;
    }

    @Override
    public void delLikeCommunity(LikeCommunityParam likeCommunityParam) {
        likeCommunityMapper.delLikeMC(likeCommunityParam);
    }
}
